package com.project.common.screens;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.trac.R;

import core.modules.DatabaseConnector;

public class Tester extends Activity {
	
	ListView list;
	ProgressBar downloadPB;
	AlertDialog.Builder dialog;
	ProgressDialog progressDialog;
	SimpleAdapter adapter;
	View v;
	
	TextView downloadedValue;

	String TAG_UID;
	String TAG_SID;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.generic_list_layout);

		new innerTask().execute();
		
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
				
				String[] to_Split = av.getItemAtPosition(pos).toString().split(", ");
				String downloadPath = to_Split[0].substring(to_Split[0].indexOf("=")+1);
				String fileName = to_Split[1].substring(to_Split[1].indexOf("=")+1);
				String header = to_Split[2].substring(to_Split[2].indexOf("=")+1, to_Split[2].indexOf("}"));
				
				doDownload(downloadPath, header, fileName);
				showProgress(fileName);
			}
		
		});
		
	}
	
	protected String doDownload(final String downloadPath, final String header, final String fileName) {
		Log.i("downloadPath", downloadPath);
		Log.i("header", header);
		Log.i("fileName", fileName);
		
		Thread dx = new Thread() {

			int fileSize = 0;
			long downloaded = 0;

			public void run() {
				File root = android.os.Environment.getExternalStorageDirectory();
				File dir = new File(root.getAbsolutePath() + "/TRAC/" + header + "/" );
				
				boolean success = true;
				
				if (!dir.exists()) {
					success = dir.mkdirs();
					dir.mkdirs();
					Log.w("Directory exists (After creation)", String.valueOf(dir.exists()));
				}
				
				if (success) {

				} else {
					// Do something else on failure 
				}
				
				try {
					URL url = new URL(downloadPath);
					URLConnection connection = url.openConnection();
					connection.connect();

					fileSize = connection.getContentLength();
					runOnUiThread(new Runnable() {
						public void run() {
							downloadPB.setMax(fileSize);
						}
					});

					InputStream input = new BufferedInputStream(url.openStream());
					OutputStream output = new FileOutputStream(dir + "/" + fileName);

					byte bufferLength[] = new byte[1024];
					int received;

					while ((received = input.read(bufferLength)) != -1) {
						downloaded += received;
						output.write(bufferLength, 0, received);
						runOnUiThread(new Runnable() {
							public void run() {
								downloadPB.setProgress((int) downloaded);
								float per = (downloaded / (float) fileSize) * 100;
								downloadedValue.setText(downloaded
										+ "/" + fileSize + "KB (" + per + "%)");
								
								if ((downloaded/fileSize) == 1) {
									dialog.setNeutralButton("Done", new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											dialog.dismiss();
										}
									});
								}
							}
						});
						
					}
					output.flush();
    				output.close();
    				input.close();

				} catch (FileNotFoundException e) {
					showError(e.getClass().toString());
				} catch (IOException e) {
					showError(e.getClass().toString());
				}
			}
		};

		dx.start();
		
		return fileName;

	}

	protected void showProgress(String fileName) {

		dialog = new AlertDialog.Builder(Tester.this);
		v = View.inflate(getApplicationContext(), R.layout.generic_progressbar, null);
		dialog.setView(v);
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setTitle("File Download");

		TextView text = (TextView) v.findViewById(R.id.fileName);
		text.setText(fileName);
		downloadedValue = (TextView) v.findViewById(R.id.download_progress);
		downloadedValue.setText("Starting download...");
		dialog.show();

		downloadPB = (ProgressBar) v.findViewById(R.id.progressBar);
		downloadPB.setProgress(0);
		downloadPB.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_state));
		
	}
	
	protected void showError(final String err) {
		runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(Tester.this, err, Toast.LENGTH_LONG).show();
			}
		});
	}
	
	private class innerTask extends AsyncTask<String, String, String> {
		
		ResultSet rs;
		
		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
		
		// keys for m
		String KEY_DOC_NAME = "fileName";
		String KEY_DOC_PATH = "downloadPath";

		String KEY_HEADER = "header";
		String header;
		
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(Tester.this);
			progressDialog.setIcon(android.R.drawable.ic_dialog_info);
			progressDialog.setMessage("Retrieving the file list, please wait.");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {
			String query = "SELECT  documents.name, documents.location, curriculum.catalognumber"
						+ " FROM curriculum"
					    + " INNER JOIN documents ON curriculum.id = documents.uploadedto"
						+ " WHERE uploadedto = "+ 24 
						+ " && uploaderid = " + 51;
			try {
					Log.w("doInBackground" , "-------- Connection is NULL! Executing query --------");
					
					rs = DatabaseConnector.getStatement().executeQuery(query);
					while (rs.next()) {
						
						header = rs.getString("catalognumber");
						DatabaseConnector.setSubDirectory(rs.getString("location"));

						m = new HashMap<String, String>();
						m.put(KEY_DOC_NAME, rs.getString("name"));
						m.put(KEY_DOC_PATH, DatabaseConnector.getSubDirectory().concat(rs.getString("name")));
						m.put(KEY_HEADER, rs.getString("catalogNumber"));
						
						arrayList.add(m);

					}
					

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {
			progressDialog.dismiss();

			runOnUiThread(new Runnable() {

				@Override
				public void run() {

					adapter = new SimpleAdapter(Tester.this, arrayList,
							R.layout.testqueries_detail, 
							new String[] { KEY_DOC_PATH, KEY_DOC_NAME, KEY_HEADER}, 
							new int[] {	R.id.header_path, R.id.header_docName });

//					TextView header_catalog = (TextView) findViewById(R.id.header_catalog);
//					header_catalog.setText(header);
					
					Log.w("onPostExecute:" , " ---------------------------------------- ");
					list.setAdapter(adapter);

				}

			});

		}

	}

}